package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.*;
import cn.wolfcode.wolf2w.query.QueryObject;
import cn.wolfcode.wolf2w.query.StrategyQuery;
import cn.wolfcode.wolf2w.redis.IStrategyRedisService;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.*;
import cn.wolfcode.wolf2w.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import io.lettuce.core.internal.LettuceClassUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static io.netty.util.internal.SystemPropertyUtil.contains;


@Service
public class StrategyServiceImpl implements IStrategyService {

    @Autowired
    private MongoTemplate template;

    @Autowired
    private StrategyRepository repository;


    @Autowired
    private StrategyThemeRepository tRepository;

    @Autowired
    private IStrategyCatalogService strategyCatalogService;

    @Autowired
    private IStrategyThemeService strategyThemeService;

    @Autowired
    private IDestinationService destinationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IStrategyRedisService strategyRedisService;



    @Override
    public void update(Strategy strategy) {
        repository.save(strategy);
    }

    /**
     * 目的地分页查询
     * @return List<Strategy>
     */
    @Override
    public Page<Strategy> query(QueryObject qo) {


        // 1. 查询对象
        Query query = new Query();

        // 2. 封装参数
        // 总条数
        long count = template.count(query, Strategy.class);
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        query.with(pageable);

        List<Strategy> list = template.find(query, Strategy.class);

        return new PageImpl<>(list,pageable,count);

    }

    /**
     * 添加/编辑攻略主题
     * @param strategy
     */
    @Override
    public void saveOrUpdate(Strategy strategy) {

        // 通过查询攻略分类对象得到目的地的id和名字
        if (StringUtils.hasLength(strategy.getCatalogId())) {
            StrategyCatalog catalog = strategyCatalogService.get(strategy.getCatalogId());
            strategy.setDestId(catalog.getDestId());    // 目的地id
            strategy.setDestName(catalog.getDestName());    // 目的地名称
            strategy.setCatalogName(catalog.getName());     // 分类名称
        }
        // 主题名称
        StrategyTheme theme = strategyThemeService.get(strategy.getThemeId());
        strategy.setThemeName(theme.getName());     // 主题名称

        // 是否国外
        if(StringUtils.hasLength(strategy.getDestId())){
            List<Destination> destinations = destinationService.queryToasts(strategy.getDestId());
            if ("中国".equals(destinations.get(0))){
                strategy.setIsabroad(1);
            }else {
                strategy.setIsabroad(0);
            }
        }

        if (StringUtils.hasLength(strategy.getId())){   // id不为空,更新操作
            // 编辑时,需要保留更新前的数据 如: 评论数,点击量 否则会被初始化为0
            Strategy str = this.get(strategy.getId());
            strategy.setCreateTime(str.getCreateTime());
            strategy.setReplynum(str.getReplynum());
            strategy.setFavornum(str.getFavornum());
            strategy.setThumbsupnum(str.getThumbsupnum());
            strategy.setSharenum(str.getSharenum());
            strategy.setViewnum(str.getViewnum());
            repository.save(strategy);
        }else {         //新增操作
            strategy.setCreateTime(new Date());
            strategy.setId(null);
            repository.save(strategy);
        }
    }




    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public List<StrategyTheme> getThemes() {
        return tRepository.findAll();
    }

    @Override
    public Strategy get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<Strategy> findByCatalogId(String catalogId, Pageable pageable) {
        return repository.findByCatalogId(catalogId,pageable);
    }

    @Override
    public List<Strategy> queryStrategies(String destId) {
        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC,"viewnum");
        //显示 点击量前3
        List<Strategy> strategies = repository.findByDestId(destId,pageable);
        return strategies;
    }

    @Override
    public Page queryStrategiesByDestId(StrategyQuery qo) {
        Query query = new Query();

        //上级id
        if (StringUtils.hasLength(qo.getDestId())){
            query.addCriteria(Criteria.where("destId").is(qo.getDestId()));
        }
        //主题id
        if (StringUtils.hasLength(qo.getThemeId())){
            query.addCriteria(Criteria.where("themeId").is(qo.getThemeId()));
        }

        long count = template.count(query, StrategyTheme.class);
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(),
                Sort.Direction.ASC, "_id");

        query.with(pageable);

        List<Strategy> list = template.find(query, Strategy.class);

        return new PageImpl<>(list,pageable,count);

    }

    @Override
    public void addViewnum(String id) {

        // 调用获取vo对象的方法
        StrategyStatisVO statisVo = this.getStatisVo(id);

        // 给VO对象中的viewnum + 1
        statisVo.setViewnum(statisVo.getViewnum()+1);
        // 重新把VO对象缓存到redis中
        strategyRedisService.setStatisVo(id,statisVo);
//        String voStr = JSON.toJSONString(statisVo);
//        redisTemplate.opsForValue().set(RedisKeys.STRATEGY_STATIS.join(id),voStr);

    }
    @Override
    public StrategyStatisVO getStatisVo(String id) {
        // 准备一个空的统计VO对象
        StrategyStatisVO strategyStatisVO = new StrategyStatisVO();

        // 拿到当前攻略的id 凭借成redis中的key
        String key = RedisKeys.STRATEGY_STATIS.join(id);
        // 判断key是否存在redis缓存中
        if (!redisTemplate.hasKey(key)) {
            // 若不存在,则初始化VO对象
            Strategy strategy = this.get(id);
            BeanUtils.copyProperties(strategy,strategyStatisVO);
        }else { // 若存在则直接获取vo对象
            String voStr = redisTemplate.opsForValue().get(key);
            strategyStatisVO = JSON.parseObject(voStr,StrategyStatisVO.class);
        }
        return strategyStatisVO;
    }

    @Override
    public void addReplynum(String strategyId) {
        // 调用获取vo对象的方法
        StrategyStatisVO vo = this.getStatisVo(strategyId);
        // 给vo对象中的replynum +1
        vo.setReplynum(vo.getReplynum()+1);
        // 重新将vo 对象缓存到redis中
        strategyRedisService.setStatisVo(strategyId,vo);
    }

    @Override
    public boolean favor(String sid, UserInfo userInfo) {
        // 获取当前登录用户id,拼接成key
        String key = RedisKeys.USER_STRATEGY_FAVOR.join(userInfo.getId());
        List sidList = new ArrayList();
        // 判断redis缓存中是否存在该记号集合
        if (redisTemplate.hasKey(key)) {    // 若存在,则直接获取
            // 从redis中取出记号集合
            String favorsStr = redisTemplate.opsForValue().get(key);
            sidList = JSON.parseObject(favorsStr, List.class);
        }
        StrategyStatisVO vo = this.getStatisVo(sid);
        // 判断攻略sid是否存在于记号集合中
        if (sidList.contains(sid)) {
            // 存在,则表示此次操作为取消收藏,攻略收藏数 -1 ,记号(sid)从记号集合(sidList)中移除
            vo.setFavornum(vo.getFavornum() -1 );
            sidList.remove(sid);
        }else {
            // 若不存在,则表示该操作为收藏操作,攻略收藏 +1 , 记号添加到记号集合中
            vo.setFavornum(vo.getFavornum() + 1);
            sidList.add(sid);
        }
        // 将记号集合和vo对象分别缓存到redis中
        redisTemplate.opsForValue().set(key, JSON.toJSONString(sidList));
        strategyRedisService.setStatisVo(sid,vo);
        return sidList.contains(sid);
    }

    @Override
    public boolean strategyThumbup(String sid, UserInfo userInfo) {
        String uid = userInfo.getId();
        //使用攻略sid和用户uid拼接成key
        String key = RedisKeys.USER_STRATEGY_THUMBSUP.join(sid, uid);
        // 判断redis缓存中是否存在这个key
        if (redisTemplate.hasKey(key)) {    // 如果存在,则表示已赞(顶)过
            return false;
        }
        // 不存在则表示今天还没顶  点赞数 +1
        StrategyStatisVO vo = this.getStatisVo(sid);
        vo.setThumbupnum(vo.getThumbupnum() + 1);
        // 重新将vo对象缓存到redis中
        redisTemplate.opsForValue().set(RedisKeys.STRATEGY_STATIS.join(sid), JSON.toJSONString(vo));
        // 将点赞的key缓存到redis中做记号,并设置有效时间,表示今天已经顶过
        redisTemplate.opsForValue().set(key,"1",RedisKeys.USER_STRATEGY_THUMBSUP.getTime(),TimeUnit.SECONDS);
        return true;
    }

    @Override
    public List<Strategy> list() {

        return repository.findAll();
    }

    @Override
    public void updateStrategyVo(StrategyStatisVO vo) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(vo.getStrategyId()));

        Update update = new Update();
        update.set("viewnum",vo.getViewnum());
        update.set("replynum",vo.getReplynum());
        update.set("favornum",vo.getFavornum());
        update.set("sharenum",vo.getSharenum());
        update.set("thumbsupnum",vo.getThumbupnum());

        template.updateMulti(query,update,Strategy.class);
    }
}
